<template>
  <div class="player-page">
    <!-- 顶部区域 -->
    <div class="header-section">
      <div class="back-button" @click="$router.go(-1)">
        <i class="el-icon-arrow-left"></i> 返回
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧封面和信息 -->
      <div class="left-section">
        <div class="cover-container">
          <img
            :src="currentSong.imgUrl || require('@/assets/logo/logo.png')"
            class="album-cover"
            :class="{ rotating: isPlaying }"
          />
        </div>
        <div class="song-info">
          <h1 class="song-name">{{ currentSong.songName || "暂无播放" }}</h1>
          <p class="artist-name">{{ currentSong.singer || "未知歌手" }}</p>
        </div>
      </div>

      <!-- 右侧歌词区域 -->
      <div class="right-section">
        <div class="lyrics-container" ref="lyricsContainer">
          <div
            class="lyrics-content"
            :style="{
              transform: `translateY(-${currentLyricIndex * lineHeight}px)`,
            }"
          >
            <p
              v-for="(line, index) in formattedLyrics"
              :key="index"
              class="lyric-line"
              :class="{ active: currentLyricIndex === index }"
            >
              {{ line }}
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- 评论对话框 -->
    <transition name="slide-up">
      <div v-if="showCommentDialog" class="comment-dialog">
        <div class="dialog-content">
          <!-- 评论展示列表 -->
          <div class="comments-display">
            <h3>评论列表</h3>
            <div class="comments-list">
              <div
                v-for="(comment, index) in comments"
                :key="index"
                class="comment-item"
              >
                <img :src="comment.avatar" class="user-avatar" />
                <div class="comment-content">
                  <div class="user-info">
                    <span class="user-name">{{ comment.userName }}</span>
                    <span class="comment-time">{{ comment.createTime }}</span>
                  </div>
                  <p class="comment-text">{{ comment.content }}</p>
                </div>
              </div>
            </div>
          </div>

          <h3>发表评论</h3>
          <textarea
            v-model="newComment"
            placeholder="输入你的评论..."
          ></textarea>
          <button @click="submitComment()">提交评论</button>
          <button @click="(showCommentDialog = false), (show = true)">
            关闭
          </button>
        </div>
      </div>
    </transition>

    <!-- 底部控制区域 -->
    <div class="control-section">
      <div class="progress-bar">
        <span class="time">{{ formatTime(currentTime) }}</span>
        <el-slider
          v-if="show"
          v-model="progress"
          @change="handleProgressChange"
          :format-tooltip="formatTime"
        ></el-slider>
        <span class="time">{{ formatTime(duration) }}</span>
      </div>

      <div class="control-buttons">
        <!-- 收藏按钮 -->
        <div class="favorite-btn" @click="toggleFavorite">
          <i :class="isFavorited ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
          <!-- <span>{{ isFavorited ? "已收藏" : "收藏" }}</span> -->
        </div>
        <!-- 评论图标 -->
        <div class="comment-icon" @click="listCommentVo()">
          <i class="el-icon-s-comment"></i>
          <span class="comment-count">{{ commentCount }}</span>
        </div>
        <i class="el-icon-arrow-left control-btn" @click="prevSong"></i>
        <div class="play-pause-btn" @click="togglePlay">
          <i
            :class="isPlaying ? 'el-icon-video-pause' : 'el-icon-video-play'"
          ></i>
        </div>
        <i class="el-icon-arrow-right control-btn" @click="nextSong"></i>
        <div class="replay-btn" @click="replaySong">
          <i class="el-icon-refresh" title="重播"></i>
        </div>
        <div class="volume-control">
          <i class="el-icon-microphone"></i>
          <el-slider
            v-if="show"
            v-model="volume"
            @change="handleVolumeChange"
            :max="100"
            :min="0"
          ></el-slider>
        </div>
      </div>
    </div>

    <!-- 音乐列表图标 -->
    <div class="music-list-icon" @click="toggleMusicList">
      <img src="@/assets/images/musicList.png" alt="音乐列表" />
    </div>

    <!-- 音乐列表弹出框 -->
    <transition name="slide">
      <div v-if="showMusicList" class="music-list">
        <h3>播放列表</h3>
        <ul>
          <li
            v-for="(song, index) in songList"
            :key="index"
            :class="{ active: currentSongIndex === index }"
            @click="playSong(index)"
          >
            {{ song.songName }} - {{ song.singer }}
          </li>
        </ul>
        <button @click="toggleMusicList">关闭</button>
      </div>
    </transition>

    <!-- 音频元素 -->
    <audio
      ref="audioElement"
      :src="currentSong.fileUrl"
      @timeupdate="handleTimeUpdate"
      @ended="handleSongEnd"
      @loadedmetadata="handleLoadedMetadata"
      :autoplay="isPlaying"
    ></audio>
  </div>
</template>

<script>
import { getSong, getWaitingSongList } from "@/api/song/song";
import { listCommentVo, getCommentCount } from "@/api/comment/comment";
import { addComment } from "@/api/comment/comment";
import { Message } from "element-ui"; // 引入提示框
import {
  addFavorite,
  delFavorite2,
  getFavoriteStatus,
} from "@/api/favorite/favorite";
export default {
  name: "MusicPlayer",
  data() {
    return {
      songList: [],
      currentSongIndex: 0,
      //待播放歌曲列表
      waitingSongs: [],
      songIds: [], // 存储歌手的模块播放所有歌曲ID的数组
      //评论数目
      commentCount: 0,
      // 用户评论列表
      comments: null,
      show: true,
      currentSong: {},
      isPlaying: true,
      currentTime: 0,
      duration: 0,
      volume: 60,
      progress: 0,
      playMode: "sequence", // sequence, loop, random
      // 给歌词赋予初值
      lyrics: "暂无歌词",
      currentLyricIndex: 0,
      showCommentDialog: false, // 控制评论对话框的显示
      newComment: "", // 存储新评论内容
      isFavorited: "", // 跟踪收藏状态
      commentCount: "", // 跟踪评论数量
      showMusicList: false, // 控制音乐列表的显示
      upcomingSongs: [], // 存储即将播放的歌曲
      lineHeight: 30, // 每行歌词的高度
    };
  },
  computed: {
    playModeIcon() {
      const modes = {
        sequence: "el-icon-refresh-right",
        loop: "el-icon-refresh",
        random: "el-icon-refresh-left",
      };
      return modes[this.playMode];
    },
    formattedLyrics() {
      return this.lyrics.split("\n");
    },
  },
  created() {
    this.songIds = this.$route.query.songIds;
    this.currentSongIndex = this.$route.query.currentSongIndex;

    //播放songIds里的音乐,同时将音乐放入待播放歌曲列表
    this.songIds.forEach((id) => {
      this.waitingSongs.push(id);
    });
    this.getSong(this.waitingSongs[this.currentSongIndex]);
    this.getCommentCount();
    this.getFavoriteStatus();
    this.togglePlay();
    this.fetchUpcomingSongs(); // 获取即将播放的歌曲
  },
  methods: {
    getCommentCount() {
      // console.log(
      //   "获取的评论的歌曲id为 :",
      //   this.waitingSongs[this.currentSongIndex]
      // );
      getCommentCount(this.waitingSongs[this.currentSongIndex]).then((res) => {
        this.commentCount = res;
        // console.log("获取的评论数目为:", res);
      });
    },
    toggleFavorite() {
      this.isFavorited = !this.isFavorited; // 切换收藏状态
      const message = this.isFavorited ? "已收藏" : "已取消收藏";
      const messageType = this.isFavorited ? "success" : "warning"; // 根据收藏状态设置消息类型
      Message({
        message: message,
        type: messageType, // 设置消息类型
      });
      const data = {
        userId: localStorage.getItem("userId"),
        songId: this.waitingSongs[this.currentSongIndex],
      };
      // console.log("获取的收藏音乐为:", data);
      if (this.isFavorited) {
        addFavorite(data).then((response) => {
          // 更新收藏状态
          // console.log("获取的response为:", response);
        });
        //添加用户的行为信息到本地存储
        const index = localStorage.getItem("index");
        localStorage.removeItem("index");

        const userActionData = JSON.stringify({
          userId: localStorage.getItem("userId"),
          songId: this.waitingSongs[this.currentSongIndex],
          action: "favorite",
        });
        localStorage.setItem(parseInt(index) + 1, userActionData);

        //index加一
        localStorage.setItem("index", parseInt(index) + 1);
      } else {
        delFavorite2(data).then((response) => {
          // 更新收藏状态
          // console.log("获取的response为:", response);
        });
      }
    },

    //获取评论数据的数目
    submitComment() {
      if (this.newComment.trim()) {
        const data = {
          userId: localStorage.getItem("userId"),
          songId: this.waitingSongs[this.currentSongIndex],
          content: this.newComment,
        };
        addComment(data).then((res) => {
          //提示评论成功
          this.$message.success("评论成功");
          this.newComment = ""; // 清空输入框
          this.listCommentVo();
        });
      } else {
        alert("评论内容不能为空");
      }
    },
    //获取歌曲信息
    getSong(songId) {
      getSong(songId).then((res) => {
        // console.log("成功获取歌曲信息", res.data);
        this.currentSong = res.data;
        this.lyrics = res.data.lyric;
      });
    },
    // 获取评论
    listCommentVo() {
      this.show = false;
      this.showCommentDialog = true;
      listCommentVo(this.waitingSongs[this.currentSongIndex]).then((res) => {
        this.comments = res;
      });
    },
    // 在播放或暂停时
    togglePlay() {
      if (this.isPlaying) {
        this.$refs.audioElement.pause(); // 暂停音频
        this.isPlaying = false; // 更新播放状态
      } else {
        this.$refs.audioElement.play(); // 播放音频
        this.isPlaying = true; // 更新播放状态
      }
    },

    // 上一首
    prevSong() {
      this.isPlaying = false;
      console.log(
        "上一首歌曲的id为：" + this.waitingSongs[this.waitingSongs.length - 1]
      );
      //判断如果小于于0，则从待播放歌曲列表的末尾开始播放
      if (this.currentSongIndex == 0) {
        // console.log("当前这个歌曲的index为：" + this.currentSongIndex);
        this.currentSongIndex = this.waitingSongs.length - 1;
        this.getSong(this.waitingSongs[this.currentSongIndex--]);
        this.getCommentCount();
        this.togglePlay();
      }
      this.getSong(this.waitingSongs[this.currentSongIndex--]);
      this.getCommentCount();
      this.togglePlay();
    },

    // 下一首
    nextSong() {
      this.isPlaying = false;
      //判断如果超出了待播放歌曲列表的长度，则从头开始播放
      if (this.currentSongIndex == this.waitingSongs.length) {
        this.currentSongIndex = 0;
      }
      // console.log("歌曲的index为：" + this.currentSongIndex);
      this.getSong(this.waitingSongs[this.currentSongIndex++]);
      this.getCommentCount();
      this.togglePlay();
    },

    // 切换播放模式
    togglePlayMode() {
      const modes = ["sequence", "loop", "random"];
      const currentIndex = modes.indexOf(this.playMode);
      this.playMode = modes[(currentIndex + 1) % modes.length];
    },

    // 进度条控制
    handleProgressChange(value) {
      const time = (value / 100) * this.duration;
      this.$refs.audioElement.currentTime = time;
    },

    // 音量控制
    handleVolumeChange(value) {
      this.$refs.audioElement.volume = value / 100;
    },

    // 时间更新处理
    handleTimeUpdate() {
      this.currentTime = this.$refs.audioElement.currentTime;
      this.progress = (this.currentTime / this.duration) * 100;

      // 更新当前歌词索引
      const newIndex = Math.floor(
        this.currentTime / (this.duration / this.formattedLyrics.length)
      );
      if (newIndex !== this.currentLyricIndex) {
        this.currentLyricIndex = newIndex;
      }
    },

    // 歌曲结束处理
    handleSongEnd() {
      if (this.playMode === "loop") {
        this.$refs.audioElement.currentTime = 0;
        this.$refs.audioElement.play();
      } else {
        this.nextSong();
      }
    },

    // 元数据加载完成
    handleLoadedMetadata() {
      this.duration = this.$refs.audioElement.duration;
    },

    // 格式化时间
    formatTime(seconds) {
      const mins = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${mins.toString().padStart(2, "0")}:${secs
        .toString()
        .padStart(2, "0")}`;
    },

    // 重播当前歌曲
    replaySong() {
      this.$refs.audioElement.currentTime = 0; // 将当前时间设置为0
      this.$refs.audioElement.play(); // 播放音频
    },

    getFavoriteStatus() {
      const data = {
        userId: localStorage.getItem("userId"),
        songId: this.waitingSongs[this.currentSongIndex],
      };
      getFavoriteStatus(data).then((res) => {
        if (res === 0) {
          this.isFavorited = false;
        } else {
          this.isFavorited = true;
        }
      });
    },
    toggleMusicList() {
      this.showMusicList = !this.showMusicList; // 切换音乐列表的显示状态
      //获取待播放的音乐列表
      getWaitingSongList(this.waitingSongs).then((res) => {
        this.songList = res;
        // console.log("待播放列表", res);
      });
    },
    // 假设有一个方法来获取即将播放的歌曲
    fetchUpcomingSongs() {
      // 这里可以调用API获取即将播放的歌曲
      this.upcomingSongs = [
        { name: "歌曲1", artist: "歌手1" },
        { name: "歌曲2", artist: "歌手2" },
        // 添加更多歌曲...
      ];
    },
    playSong(index) {
      this.currentSongIndex = index; // 更新当前歌曲索引
      this.getSong(this.waitingSongs[this.currentSongIndex]); // 获取新歌曲信息
      this.togglePlay(); // 播放新歌曲
    },
  },

  beforeDestroy() {
    this.$refs.audioElement?.pause();
  },
};
</script>

<style scoped>
.comment-count {
  font-size: 14px;
}
.player-page {
  background-color: #282c34; /* 背景颜色 */
  color: #fff; /* 字体颜色 */
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header-section {
  background-color: #1c1e22; /* 顶部区域背景颜色 */
  padding: 10px;
}

.back-button {
  color: #fff;
  cursor: pointer;
}

.main-content {
  display: flex;
  flex: 1;
  padding: 20px;
}

.left-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.cover-container {
  width: 300px;
  height: 300px;
  margin-bottom: 30px;
}

.album-cover {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
}

.rotating {
  animation: rotate 20s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.song-info {
  text-align: center;
}

.song-name {
  font-size: 24px;
  margin-bottom: 10px;
}

.artist-name {
  font-size: 16px;
  color: #999;
}

.right-section {
  flex: 1;
  overflow: hidden;
}

.lyrics-container {
  height: 400px; /* 固定高度 */
  overflow: hidden; /* 隐藏超出部分 */
  position: relative; /* 相对定位 */
}

.lyrics-content {
  transition: transform 0.5s ease; /* 平滑过渡效果 */
}

.lyric-line {
  text-align: center;
  margin: 20px 0;
  color: #999;
  transition: all 0.3s;
}

.lyric-line.active {
  color: #fff;
  font-size: 18px;
  font-weight: bold;
}

.control-section {
  padding: 20px;
}

.progress-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.time {
  font-size: 12px;
  color: #999;
  width: 45px;
}

.el-slider {
  flex: 2;
}

.control-buttons {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 30px;
}

.control-btn {
  font-size: 24px;
  cursor: pointer;
  color: #fff;
}

.play-pause-btn {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: #ff4e4e;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 24px;
}

.volume-control {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 150px;
}

.comment-icon {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #fff;
  /* margin-right: 20px; */
}

.comment-dialog {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.9);
  padding: 20px;
  padding-top: 10px;
  border-top-left-radius: 10px;
  border-top-right-radius: 10px;
}

.dialog-content {
  display: flex;
  flex-direction: column;
}

.dialog-content h3 {
  margin: 0 0 10px;
  color: #fff;
}

.dialog-content textarea {
  height: 30px;
  margin-bottom: 10px;
  padding: 10px;
  border-radius: 5px;
  border: none;
}

.dialog-content button {
  margin-top: 5px;
  padding: 10px;
  background-color: #ff4e4e;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.dialog-content button:hover {
  background-color: #ff2e2e;
}

.comments-display {
  margin-top: 20px;
}

.comments-list {
  max-height: 200px;
  overflow-y: auto;
  margin-bottom: 10px;
}

.comment-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
  padding: 10px;
  background-color: rgba(255, 255, 255, 0.1);
  border-radius: 8px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.comment-content {
  flex: 1;
}

.user-info {
  display: flex;
  justify-content: space-between;
}

.user-name {
  font-weight: bold;
  color: #fff;
}

.comment-time {
  font-size: 12px;
  color: #999;
}

.comment-text {
  color: #fff;
  margin-top: 5px;
}

.favorite-btn {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #fff;
  margin-right: 20px;
}

.favorite-btn i {
  font-size: 24px;
  margin-right: 5px;
}

.music-list-icon {
  position: fixed;
  bottom: 25px;
  right: 50px;
  cursor: pointer;
}

.music-list {
  position: fixed;
  right: 0;
  top: 0;
  width: 300px;
  height: 100%;
  background: rgba(30, 30, 30, 0.9); /* 更深的背景色 */
  color: #fff;
  padding: 20px;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.7); /* 更明显的阴影效果 */
  border-left: 1px solid rgba(255, 255, 255, 0.1); /* 添加左边框 */
  overflow-y: auto; /* 允许滚动 */
}

.music-list h3 {
  margin: 0 0 15px; /* 增加标题下方的间距 */
  font-size: 20px; /* 增加标题字体大小 */
  text-align: center; /* 居中对齐 */
}

.music-list ul {
  list-style: none;
  padding: 0;
}

.music-list li {
  margin: 15px 0; /* 增加每首歌曲之间的间距 */
  padding: 10px; /* 增加内边距 */
  background: rgba(255, 255, 255, 0.1); /* 每首歌曲的背景色 */
  border-radius: 5px; /* 圆角效果 */
  transition: background 0.3s; /* 背景色过渡效果 */
  cursor: pointer; /* 鼠标悬停时显示为可点击 */
}

.music-list li:hover {
  background: rgba(255, 255, 255, 0.2); /* 悬停时的背景色变化 */
}

.music-list li.active {
  background: rgba(255, 255, 0, 0.3); /* 正在播放的歌曲高亮显示 */
  font-weight: bold; /* 高亮歌曲加粗 */
}
</style>
